import React, { useState } from 'react';
import { Layout, Button, Modal, Input, Space } from 'antd';
import RecordList from './RecordList';
import RecordForm from './RecordForm';

const { Header, Content, Footer } = Layout;
const { Search } = Input;

interface Record {
    id: number;
    bookName: string;
    borrower: string;
    borrowDate: string;
    returnDate: string;
}

const Records: React.FC = () => {
    const [records, setRecords] = useState<Record[]>([]);
    const [currentRecord, setCurrentRecord] = useState<Record | null>(null);

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [searchText, setSearchText] = useState('');

    const handleAdd = () => {
        setCurrentRecord(null);
        setIsModalVisible(true);
    };

    const handleEdit = (record: Record) => {
        setCurrentRecord(record);
        setIsModalVisible(true);
    };

    const handleDelete = (id: number) => {
        setRecords(records.filter(record => record.id !== id));
    };

    const handleSave = (record: Record) => {
        if (currentRecord) {
            setRecords(records.map(r => (r.id === currentRecord.id ? { ...record, id: currentRecord.id } : r)));
        } else {
            setRecords([...records, { ...record, id: Date.now() }]);
        }
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const handleSearch = (value: string) => {
        setSearchText(value);
    };

    const filteredRecords = records.filter(record =>
        record.bookName.toLowerCase().includes(searchText.toLowerCase()) ||
        record.borrower.toLowerCase().includes(searchText.toLowerCase())
    );

    return (
        <div>
            <Space style={{ marginBottom: '20px' }}>
                <Search
                    placeholder="搜索书名或借阅人"
                    onSearch={handleSearch}
                    style={{ width: 300, marginRight: 16 }}
                />
                <Button type="primary" onClick={handleAdd}>
                    添加记录
                </Button>

            </Space>
            <RecordList records={filteredRecords} onEdit={handleEdit} onDelete={handleDelete} />
            <Modal
                title={currentRecord ? '编辑记录' : '添加记录'}
                visible={isModalVisible}
                footer={null}
                onCancel={handleCancel}
            >
                <RecordForm record={currentRecord} onSave={handleSave} onCancel={handleCancel} />
            </Modal>
        </div>
    );
};

export default Records;